import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { DNavBar, DModal, DPaymodel } from '@/components'
import DHeader from './component/header'
import DContent from './component/content'
import DList from './component/list'
import DFooter from './component/footer'
import classNames from 'classnames'
import http from '@/api'
import sdk from '@/common/sdk'
import dayjs from 'dayjs'
import './itemdetail.scss'
const getUrlScheme = http.getUrlScheme

const bgImages = require('../assets/bgImages.png')

export default class DItemdetail extends Component {

  constructor(props) {
    super(props)
    this.state = {
      title: "托运订单",
      // headerInfo: {},
      id: '',
      status: '',
      isShow: false,
      item: {},
      headerobj: {
        itemtime: {
          isShowDay: false,
          isShowHour: true,
          day: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        }
      },
      firstList: {
        info: [
          {
            label: "承运方企业",
            value: ""
          },
          {
            label: "承运方联系人",
            value: ""
          },
          {
            label: "  联系方式",
            value: ""
          }
        ]
      },
      secondList: {
        title: "始发地信息",
        info: [
          {
            label: "始发地联系人",
            value: ""
          },
          {
            label: "联系方式",
            value: ""
          },
          {
            label: "始发地地址",
            value: ""
          }
        ]
      },
      threeList: {
        title: "目的地信息",
        info: [
          {
            label: "目的地联系人",
            value: ""
          },
          {
            label: "联系方式",
            value: ""
          },
          {
            label: "目的地地址",
            value: ""
          }
        ]
      },
      fourList: {
        title: "运输信息",
        info: [
          {
            label: "运输费用",
            value: ""
          },
          {
            label: "发车日期",
            value: ""
          },
          {
            label: "托运车辆1",
            value: ""
          },
          {
            label: "车架号1",
            value: ""
          }
        ]
      },
      fiveList: {
        info: [
          {
            label: "托运车辆2",
            value: ""
          },
          {
            label: "车架号2",
            value: ""
          }
        ]
      },
      sixList: {
        info: [
          {
            label: "备注",
            value: ""
          }
        ]
      }
    }
  }

  componentWillMount() {
    let { id, status } = this.$router.params
    this.getDetailInfo(id)
    this.setState({
      headerobj: {
        title: this.getStatus(status)
      },
      id,
      status
    })
    if (window.localStorage.getItem('ISPAY')) {
      // this.state.isOpened： = true
      this.setState({
        isOpened: true
      }, () => window.localStorage.removeItem('ISPAY'))
    }
  }

  componentDidShow() {
    sdk.setTitleInfo(this.state.title)
  }

  getDetailInfo(id) {
    http.getOrderTransDetail({ id }).then(res => {
      if (res.orStatus !== this.$router.params.status) {
        Taro.showToast({
          title: '订单状态已更新',
          icon: 'none'
        }).then(date => {
          Taro.redirectTo({
            url: `/pages/itemdetail/itemdetail?id=${res.id}&status=${res.orStatus}`
          })
        })
      }
      // console.log("res-->", res)
      let { firstList, secondList, threeList, fourList, fiveList, sixList } = this.state

      let _firstList = ['orSaleComp', 'orSale', 'orSaleContact']
      firstList.info.map((item, i) => {
        item.value = res[_firstList[i]]
      })

      let _secondList = ['cdStartConner', 'cdStartPhone', 'cdStartAddr']
      secondList.info.map((item, i) => {
        item.value = res[_secondList[i]]
      })

      let _threeList = ['cdEndConner', 'cdEndPhone', 'cdEndAddr']
      threeList.info.map((item, i) => {
        item.value = res[_threeList[i]]
      })

      let _fourList = ['orPrice', 'cdStartDate', 'cdCarType', 'cdCarNo']
      fourList.info.map((item, i) => {
        item.value = res[_fourList[i]] + (i === 0 ? '元' : '')
        if (_fourList[i] === 'cdCarType' && res.cdCarType.split('#').length > 1) {
          item.value = res.cdCarType.split('#')[0]
        }
        if (_fourList[i] === 'cdCarNo' && res.cdCarNo.split('#').length > 1) {
          item.value = res.cdCarNo.split('#')[0]
        }
      })
      let _fiveList = ['cdCarType', 'cdCarNo']
      fiveList.info.map((item, i) => {
        item.value = res[_fiveList[i]].split('#')[1]
      })

      let _sixList = ['cdRemark']
      sixList.info.map((item, i) => {
        item.value = res[_sixList[i]] || '(空)'
      })

      //根据订单状态计算倒计时
      let orStatus = this.$router.params.status
      let times = ''
      if (orStatus === '11') {
        let createTime = dayjs(res.updateTime).add(3, 'minute')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else if (orStatus === '21') {
        let createTime = dayjs(res.createTime).add(30, 'minute')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else if (orStatus === '42') {
        let createTime = dayjs(res.updateTime).add(3, 'day')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else {
        times = 0
      }
      this.setState({
        // headerInfo: Object.assign(this.state.headerInfo, _headeInfo),
        firstList,
        headerobj: {
          ...this.state.headerobj,
          account: res.orNo,
          text: this.getText(orStatus),
          tiptext: this.getPlatformTxt(orStatus),
          itemtime: {
            isShowDay: false,
            isShowHour: true,
            day: times,
            hours: 0,
            minutes: 0,
            seconds: 0
          }
        }
      })
      // debugger
    })
  }

  getStatus(status) {
    return {
      $11: "待支付",
      $21: "待承运方接单",
      $31: "待承运方上传",
      $32: "待确认",
      $41: "待承运方上传",
      $42: "待确认",
      $43: "待核实",
      $51: "交易成功",
      $52: "已拒接",
      $53: "已撤回",
      $54: "已超时",
      $55: "交易异常",
      $59: "待卖家同意退款",
    }[`$${status}`]
  }
  getPlatformTxt(orstatu) {
    return {
      $11: '系统将自动取消订单',
      $21: '系统将自动拒绝接单',
      $31: '请耐心等候',
      $41: '请耐心等候',
      $42: '系统将自动确认',
      // $43: '将自动确认'
    }[`$${orstatu}`]
  }
  getText(orstatu) {
    return {
      $11: '请支付运输费用',
      $21: '请等待卖家接单',
      $31: '承运方将上传托运车辆照片',
      $33: '请查看验车照片查验车辆',
      $41: '交易完成后，承运方将上传合同',
      $42: '请确认承运方所上传的资料',
      $43: `平台将在<text style='font-size:20px;font-weight:bold;color:#FFAE00'>5</text>日内核实订单，逾时将自动确认`,
      $51: '亲，恭喜你成功完成一笔订单！',
      $52: '很遗憾，卖家拒接该订单',
      $53: '该订单已被您取消',
      $54: '该订单已超时',
      $55: '您的订单交易异常，平台客服已介入并终止',
      $59: '待卖家同意退款'
    }[`$${orstatu}`]
  }

  handleCarPhoto() {
    Taro.navigateTo({
      url: `/pages/checkimg/checkimg?id=${this.state.id}&status=0`
    })
  }
  handleContact() {
    Taro.navigateTo({
      url: `/pages/contractprooftran/contractprooftran?id=${this.state.id}&status=${0}`
    })
  }
  onSeconClick(item) {
    this.onHanlePay()


  }
  onHanlePay() {
    // http.getEarnestForm(params).then(res => {
    //   console.log(res)
    //   window.location.href = res.payUrl
    // }).catch(() => {
    //   Taro.showToast({
    //     title: '网络异常!',
    //     icon: "none"
    //   })
    // })
    this.setState({
      ispayShow: true,
    })
    // this.onCancelPay()
  }
  payFuc(type) {
    this.setState({
      isOpened: false
    })
    if (type) {
      Taro.redirectTo({
        url: `/pages/shoporders/shoporders?active=1`
      })
    }
  }
  handleClose() {
    this.setState({
      ispayShow: false
    })
  }
  async onCancelPay(payType = '1') {
    // let {headerobj:item} = this.state
    if (payType == 8) {
      // 小程序支付
      const urlScheme = await getUrlScheme(this.state.id, 0)
      window.location.href = urlScheme
      return
    }
    http.transPayOrder({ id: this.state.id, payIp: window.payIp, payType }).then(res => {

      setTimeout(() => {

        // Taro.navigateBack({
        //     delta: 2
        // })
        // window.localStorage.setItem('ISPAY',1)
        if (+payType === 1) {
          if (!res) {
            return Taro.showToast({
              title: '订单状态异常',
              icon: 'none'
            })
          }
          window.location.href = res
        }

        if (payType == 7) {
          let url = encodeURIComponent(res)
          return Taro.navigateTo({
            url: `/pages/wxQrCode?payUrl=${url}`
          })
        }

        // Taro.redirectTo({
        //     url: `/pages/shoporders/shoporders?active=1`
        // })
      }, 500)

    })
  }
  render
  onDraworder() {
    this.setState({
      isShow: true
    })
  }
  //撤回订单
  getBackOrder(id) {
    http.getBackOrder2({ id }).then(res => {
      Taro.redirectTo({
        url: `/pages/itemdetail/itemdetail?id=${id}&status=53`
      })
    })
  }
  onClose() {
    this.setState({
      isShow: false
    })
  }
  onLastHandle() {
    let { id } = this.state
    this.onClose()
    this.getBackOrder(id)
  }
  onConfirmCar() {
    Taro.redirectTo({
      url: `/pages/checkimg/checkimg?id=${this.state.id}&status=1`
    })
  }
  onConfirmProof() {
    Taro.redirectTo({
      url: `/pages/contractprooftran/contractprooftran?id=${this.state.id}&status=1`
    })
  }
  render() {
    const {
      title,
      firstList,
      secondList,
      threeList,
      fourList,
      fiveList,
      sixList,
      status,
      isShow,
      headerobj
    } = this.state
    const dlist1 = { list: [{ title: '验车照片' }] }
    const dlist2 = { list: [{ title: '合同凭证' }] }
    return (
      <View className='b_itemdetail'>
        <Image src={bgImages} className={classNames('b_itemdetail__imagebs', process.env.NODE_ENV === 'development' ? '' : 'b_itemdetail__NODEimg')}></Image>
        <DNavBar title={title} className='b_itemdetail__nav'></DNavBar>
        <View className='b_itemdetail__box'>
          <View className='b_itemdetail__content'>
            <DHeader {...headerobj}></DHeader>
            <DContent {...firstList}></DContent>
            <DContent {...secondList}></DContent>
            <DContent {...threeList}></DContent>
            <DContent {...fourList}></DContent>
            {fiveList.info[0].value && <DContent {...fiveList}></DContent>}
            <DContent {...sixList}></DContent>
            {status > 33 && status < 52 &&
              <DList {...dlist1} handleClick={this.handleCarPhoto.bind(this)}></DList>
            }
            {status > 41 && status < 52 &&
              <DList {...dlist2} handleClick={this.handleContact.bind(this)}></DList>
            }
            {status === '11' &&
              <DFooter secondText='支付费用' onSeconClick={this.onSeconClick.bind(this,)}></DFooter>
            }
            {status === '21' &&
              <DFooter firstText='撤回订单' onFirstClick={this.onDraworder.bind(this)}></DFooter>
            }
            {status === '32' &&
              <DFooter secondText='确认验车' onSeconClick={this.onConfirmCar.bind(this, firstList)}></DFooter>
            }
            {status === '42' &&
              <DFooter secondText='确认合同' onSeconClick={this.onConfirmProof.bind(this)}></DFooter>
            }
          </View>
        </View>
        <DModal
          isShow={isShow}
          title='提示'
          text='确认撤回订单吗？'
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>
        <DPaymodel handleClose={this.handleClose.bind(this)} onCancel={this.onCancelPay.bind(this)} isShow={this.state.ispayShow} />
      </View>
    )
  }
}
